<template>
	<div class="login"></div>
</template>

<script>
	import {
		setToken,
		removeToken
	} from '@/utils/auth'
	import {
		Dialog
	} from "vant";

	import {
		getUser
	} from '@/api/user'

	export default {
		name: "Login",
		created() {
			if (this.getQueryVariable("code")) {
				this.getLogin(this.getQueryVariable("code"));
			} else {
				this.login();
			}
		},
		methods: {
			login() {
				let appid = "wwbe514664adcfafa1";
				let redirect_uri =
					"https://wechat.accortech.cn/static/helph5/index.html";
				let url =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${encodeURI(appid)}&redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=snsapi_base#wechat_redirect`;
				window.location.href = url;
			},
			getLogin(code) {
				getUser({
					code
				}).then((res) => {
					if (res.code !== 1) {
						removeToken()
						Dialog.alert({
							title: "提示",
							message: res.msg,
						}).then(() => {});
					} else {
						setToken(res.data)
						this.$router.replace({
							path: "index"
						});
					}
				}).catch((err) => {
					console.log(err)
				})
			},
			getQueryVariable(variable) {
				var query = window.location.search.substring(1);
				var vars = query.split("&");
				for (var i = 0; i < vars.length; i++) {
					var pair = vars[i].split("=");
					if (pair[0] == variable) {
						return pair[1];
					}
				}
				return false;
			},
		},
	};
</script>